<?php
/*=============================================================================
|| ##################################################################
||	phpFoX Konsort
|| ##################################################################
||
||	Copyright		: (C) 2005-2007 PHPFOX Limited a Reality Fox Creation
||	Contact			: info@phpfox.com
||
||	- phpFoX and all of its source code and files are protected by Copyright Laws.
||
||	- The license for phpFoX permits you to install this software on a single domain (.com, .org, .net, etc.).
||
||	- You may also not remove this copyright screen which shows the copyright information and credits for phpFoX (RealityFOX Creations).
||
||	- phpFoX Konsort is NOT a FREE software - http://www.phpfox.com/license/
||
|| ##################################################################
=============================================================================*/

/* $File: ./include/modules/Gallery/classes/PhpFox_ServiceGallery.class.php, $Author:  $ */



/** Main service for gallery
 * @package module.gallery
 *
 * @version $Id: PhpFox_ServiceGallery.class.php 365 2008-02-25 18:02:46Z phpfoxsv $
 */
class PhpFox_Mod_Gallery_ServiceGallery extends BaseService
{
    function onDeleteAccount($aParams)
    {
        $oGalleryItem = $this->_oModule->getItem('Gallery');
        /* $oGalleryItem PhpFox_Mod_Gallery_ItemGallery */
        $oAccountService = &App::getModuleService('Account', 'Account');
        /* @var $oAccountService PhpFox_Mod_Account_ServiceAccount */

        $aIds = $aParams['aIds'];
        foreach ($aIds as $iUserId)
        {
            $oUser = $oAccountService->getById($iUserId);
            $aImages = $oGalleryItem->oDb->getRows('SELECT id '.
                                                  ' FROM '.App::getT('main').' '.
                                                  ' WHERE user_id = "'. $iUserId .'"');
            foreach ($aImages as $aImage)
            {
                $sSql = 'DELETE FROM '.App::getT('rating').' main = '.$aImage['id'];
                $this->deleteItem($aImage['id']);
            }
        }
    }

    /** Deleting gallery item
     * @param integer $iId item ID
     * @return boolean
     */
    function deleteItem($iId)
    {
        $oGalleryItem = $this->_oModule->getItem('Gallery');
        /* $oGalleryItem PhpFox_Mod_Gallery_ItemGallery */
        $oAccountService = &App::getModuleService('Account', 'Account');
        /* @var $oAccountService PhpFox_Mod_Account_ServiceAccount */
        $oSecurityService = &App::getModuleService('Account', 'Security');
        /* @var $oSecurityService PhpFox_Mod_Account_ServiceSecurity */
        $oCommentService = &App::getModuleService('Comments', 'Comment');
        /* @var $oCommentService PhpFox_Mod_Comments_ServiceComment */
        $iId = intval($iId);

        if ($oGalleryItem->load($iId))
        {
            $oGalleryItem->delete($iId);
            $oCommentService->onItemDelete($iId,'gallery');
            $oAccountService->changeUserInfo($oAccountService->getById($oGalleryItem->aData['user_id']), 'gallery', -1, $oGalleryItem->aData['user_id']==App::getUser('id'));
            if (file_exists(App::getParam('gallery.pic.path').$iId.'.jpg'))
            {
                @unlink(App::getParam('gallery.pic.path').$iId.'.jpg');
            }
        	if (file_exists(App::getParam('gallery.pic.path').$iId.'_view.jpg'))
            {
                @unlink(App::getParam('gallery.pic.path').$iId.'_view.jpg');
            }
            if (file_exists(App::getParam('gallery.pic.path').'thumb/'.$iId.'.jpg'))
            {
                @unlink(App::getParam('gallery.pic.path').'thumb/'.$iId.'.jpg');
            }
        }
        return true;
    }

    function getUsedSpace($iId)
    {
        $aRows = $this->oDatabase->getRows('SELECT id '.
                                            ' FROM '.App::getT('main').' '.
                                            ' WHERE user_id = "'. $iId .'"');
        $iSize = 0;
        foreach ($aRows as $aRow)
        {
            $sPath = App::getParam('gallery.pic.path');
            $iSize += (file_exists($sPath.$aRow['id'].'.jpg')) ? filesize($sPath.$aRow['id'].'.jpg') : 0;
            $iSize += (file_exists($sPath.'thumb/'.$aRow['id'].'.jpg')) ? filesize($sPath.'thumb/'.$aRow['id'].'.jpg') : 0;
        }
        return $iSize;
    }

    /** Getting list of gallery images. This method also checks permissions for gallery items
     * @param array $aCond conditions array
     * @param integer $iPage page number
     * @param integer $iPageSize items per page count
     * @param string $sSort sorting direction (in SQL format)
     * @return array [0] - items array, [1] - count of selected items
     */
    function getImageList($aCond, $iPage, $iPageSize, $sSort = '')
    {
        $oGalleryItem = $this->_oModule->getItem('Gallery');
        /* $oGalleryItem PhpFox_Mod_Gallery_ItemGallery */
        $oSecurityService = App::getModuleService('Account', 'Security');
        /* $oSecurityService PhpFox_Mod_Account_ServiceSecurity */
        $sCurrentLogin = $oSecurityService->getCurrentUserLogin();
        $sCurrentLogin = Database::escape($sCurrentLogin);
        $aMap = $oGalleryItem->aFields;
        $sCond = $oGalleryItem->_parseCond($aCond, $aMap);
        if ($sCurrentLogin && !phpfoxCache)
        {
	        $sSql = 'SELECT COUNT(DISTINCT ma.id) '.
                   ' FROM '.App::getT('main').' AS ma '.
                   ' LEFT JOIN '.App::getT('buddy').' AS bu1 '.
                   ' ON ma.user = bu1.user '.
	               ' AND ma.who_view = "friends" '.
                   ' LEFT JOIN '.App::getT('buddy').' AS bu2 '.
                   ' ON ma.user = bu2.buddy '.
	               ' AND ma.who_view = "friends" '.
                   ' WHERE ((ma.who_view = "nobody" '.
	               '   AND ma.user = "'.$sCurrentLogin.'") '.
	               '    OR (ma.who_view = "friends" '.
	               '   AND bu1.buddy = "'.$sCurrentLogin.'") '.
	               '    OR (ma.who_view = "friends" '.
	               '   AND bu2.user = "'.$sCurrentLogin.'") '.
	               '    OR ma.user = "'.$sCurrentLogin.'" '.
	               '    OR ma.who_view = "everyone") '.
	        	   '   AND '.$sCond;
        }
        else
        {
        	$sSql = 'SELECT COUNT(*) '.
				   ' FROM '.App::getT('main').' AS ma '.
	        	   ' WHERE ma.who_view = "everyone" '.
	        	   '   AND '.$sCond;
        }
        $iCnt = $oGalleryItem->oDb->getField($sSql);
        $aRows = array();
        if ($iCnt)
        {
            $iOffset = $oGalleryItem->_getOffset($iPage, $iPageSize, $iCnt);
            if ($sCurrentLogin && !phpfoxCache)
            {
            	$sSql = 'SELECT '.$oGalleryItem->_joinFields($aMap, array()).
                       ' FROM '.App::getT('main').' AS ma '.
    	               ' LEFT JOIN '.App::getT('buddy').' AS bu1 '.
                       ' ON ma.user = bu1.user '.
    	               ' AND ma.who_view = "friends" '.
                       ' LEFT JOIN '.App::getT('buddy').' AS bu2 '.
                       ' ON ma.user = bu2.buddy '.
    	               ' AND ma.who_view = "friends" '.
                       ' WHERE ((ma.who_view = "nobody" '.
    	               '   AND ma.user = "'.$sCurrentLogin.'") '.
    	               '    OR (ma.who_view = "friends" '.
    	               '   AND bu1.buddy = "'.$sCurrentLogin.'") '.
    	               '    OR (ma.who_view = "friends" '.
    	               '   AND bu2.user = "'.$sCurrentLogin.'") '.
    	               '    OR ma.user = "'.$sCurrentLogin.'" '.
    	               '    OR ma.who_view = "everyone") '.
    	        	   '   AND '.$sCond.' '.
	            	   ' GROUP BY ma.id '.
	            	   ($sSort?(' ORDER BY '.$sSort):'').
	            	   ($iPageSize?(' LIMIT '.$iOffset.','.$iPageSize):'');
            }
            else
            {
            	$sSql = 'SELECT '.$oGalleryItem->_joinFields($aMap, array()).
					   ' FROM '.App::getT('main').' AS ma '.
					   ' WHERE ma.who_view = "everyone" '.
		        	   '   AND '.$sCond.
	            	   ' GROUP BY ma.id '.
	            	   ($sSort?(' ORDER BY '.$sSort):'').
	            	   ($iPageSize?(' LIMIT '.$iOffset.','.$iPageSize):'');
            }
            $aRows = $oGalleryItem->oDb->getRows($sSql);
        }
        return array($aRows, $iCnt);
    }

    function commentsCount($iPictureId)
    {
        $oGalleryItem = $this->_oModule->getItem('Gallery');
        /* $oGalleryItem PhpFox_Mod_Gallery_ItemGallery */

        $iPictureId = intval($iPictureId);
        $iCnt = $oGalleryItem->oDb->getField('SELECT COUNT(*) '.
                                            ' FROM '.App::getT('comment').' '.
                                            ' WHERE main = '.$iPictureId);
        return $iCnt;
    }

    /** Checks that picture with $iId was rated by user $sUser
     * @param integer $iId picture ID
     * @param string $sUser user name
     * @return boolean
     */
    function isPictureRated($iId, $sUser = '')
    {
        $oGalleryItem = $this->_oModule->getItem('Gallery');
        /* $oGalleryItem PhpFox_Mod_Gallery_ItemGallery */
        $oSecurityService = App::getModuleService('Account', 'Security');
        /* $oSecurityService PhpFox_Mod_Account_ServiceSecurity */
        $iId = intval($iId);
        if (!$sUser)
        {
            $sUser = $oSecurityService->getCurrentUserLogin();
        }
        if (!$sUser)
        {
            return true;
        }
        $sUser = Database::escape($sUser);
        $bRated = $oGalleryItem->oDb->getField('SELECT COUNT(*) '.
        									  ' FROM '.App::getT('rating').' '.
        									  ' WHERE main = '.$iId.' '.
        									  '   AND user = "'.$sUser.'"');
        return $bRated;
    }

    /** Gets resolution for picture
     * @param string $sImage path to image
     * @return mixed false - if size can not be calculated, array(width, height) - if success
     */
    function getImageResolution($sImage)
    {
        if (!file_exists($sImage))
            return false;
        if ($aInfo = @getimagesize($sImage))
            return array($aInfo[0], $aInfo[1]);
        return false;
    }

    /** Recounts rating for gallery item
     * @param integer $iItemId picture ID
     * @return boolean
     */
    function updateRating($iItemId)
    {
        $oGalleryItem = $this->_oModule->getItem('Gallery');
        /* @var $oGalleryItem PhpFox_Mod_Gallery_ItemGallery */

        $iItemId = intval($iItemId);
        if (!$iItemId)
        {
        	return false;
        }
        $fAvRating = $oGalleryItem->oDb->getField('SELECT AVG(rating) '.
        										 ' FROM '.App::getT('rating').' '.
        										 ' WHERE main = '.$iItemId);
        $oGalleryItem->load($iItemId);
        $oGalleryItem->aData['rating'] = $fAvRating;
        $oGalleryItem->aData['votes']++;
        $oGalleryItem->update(array('rating', 'votes'));
        return true;
    }

    /**
     * Checks, that image with ID $iId can be viewed by current user
     *
     * @param integer $iId
     * @return boolean
     */
    function isImageAllowed($oGalleryItem)
    {
        $oFriendsService = App::getModuleService('Account', 'Friends');
        /* @var $oFriendsService PhpFox_Mod_Account_ServiceFriends */
        $oSecurityService = App::getModuleService('Account', 'Security');
        /* @var $oSecurityService PhpFox_Mod_Account_ServiceSecurity */
        $oAccountService = &App::getModuleService('Account', 'Account');
        /* @var $oAccountService PhpFox_Mod_Account_ServiceAccount */
        $iId = intval($oGalleryItem->aData['id']);

        $sCurrentUser = $oSecurityService->getCurrentUserLogin();

        if ($oGalleryItem->aData['allow'] != 0)
        {
            return false;
        }
        switch ($oGalleryItem->aData['who_view'])
        {
            case 'friends':
                $oUser = $oAccountService->getByUsername($oGalleryItem->aData['user']);
                if (!$oFriendsService->isFriend($oUser, $oSecurityService->getCurrentUser()))
                {
                    return false;
                }
                break;
            case 'nobody':
               	if ($sCurrentUser != $oGalleryItem->aData['user'])
               	{
               	    return false;
               	}
               	break;
        }
        return true;
    }

    /** Gets image size
     * @param string $sImage full path to image
     * @return integer 0 - if image not exists
     */
    function getImageSize($sImage)
    {
        if (file_exists($sImage))
        {
            return filesize($sImage);
        }
        return 0;
    }
    
    function getAccessForContent($sFile)
    {
    	$oCurUser = App::loadUser();
    	$iItemId = intval($sFile);
        if (!$iItemId)
        {
        	return false;
        }
        $oGalleryItem = $this->_oModule->getItem('Gallery');
        
        if ($oGalleryItem->load($iItemId))
        {
	        if($oGalleryItem->aData['allow'])
	        {
	        	return (App::isStaff() OR $oGalleryItem->aData['user_id'] == $oCurUser->aData['id']);
	        }
	        
	    	if(0==$oGalleryItem->aData['who_view'])
			{
				return TRUE;
			}
			
			if(1==$oGalleryItem->aData['who_view'])
			{
				$oSrvFriend = &App::getModuleService('Account', 'Friends');
				$oOwner = App::getModuleItem('Account', 'Account');
				if($oOwner->load($oGalleryItem->aData['user_id']))
				{
					return (App::isStaff() OR ($oGalleryItem->aData['user_id'] == $oCurUser->aData['id']) OR $oSrvFriend->checkIsFriend($oOwner->aData['user'],$oCurUser->aData['user']) );
				}
	        }
	    	
			if(2==$oGalleryItem->aData['who_view'])
			{
				return (App::isStaff() OR $oGalleryItem->aData['user_id'] == $oCurUser->aData['id']);
			}
        }
		return false;
    }
    
    function myGalleryCount($iUserId, $sWhoView)
    {
		static $aCnt = array();		
		if (!isset($aCnt[$iUserId]))
		{
    		$aCnt[$iUserId] = $this->oDatabase->getField('
    			SELECT COUNT(*) FROM `'. App::getT('main') .'`
        		WHERE user_id = "'. $iUserId .'" ' . $sWhoView . ' AND allow = ""
        	');    	
		}
		return $aCnt[$iUserId];
    }
}
?>